class Utils {

  // 格式化日期的方法
  formatDate(value, format) {
    //value: 需要进行格式化的数据
    //format: 日期的格式 yyyy符号MM符号dd hh符号mm符号ss
    let currentDate = new Date(value);
    let year = currentDate.getFullYear();
    if (/(y+)/.test(format)) {
      //获取组匹配的内容
      let content = RegExp.$1;
      year = year.toString().slice(4 - content.length);
      format = format.replace(content, year);
    }
    let dateObject = {
      M: currentDate.getMonth() + 1,
      d: currentDate.getDate(),
      h: currentDate.getHours(),
      m: currentDate.getMinutes(),
      s: currentDate.getSeconds()
    };
    //进行替换format
    for (let key in dateObject) {
      //根据key生成动态正则表达式
      let reg = new RegExp(`(${key}+)`);
      if (reg.test(format)) {
        //获取组的匹配内容
        let c = RegExp.$1;
        // 
        let v = dateObject[key] >= 10 ? dateObject[key] : c.length === 2 ? '0' + dateObject[key] : dateObject[key];
        format = format.replace(c, v);
      }
    }
    return format;
  }

  // 随机生成颜色
  createRandomColor() {
    let rgb = [];
    for (let i = 0; i < 3; i++) {
      let color = Math.ceil(Math.random() * 255);
      rgb.push(color);
    }
    return `rgb(${rgb.join(",")})`;
  }

  // 包括小数位的千分位处理
  addThousands(n) {
    if (!(n instanceof String)) {
      n = String(n)
    }
    var re = /\d{1,3}(?=(\d{3})+$)/g;
    var n1 = n.replace(/^(\d+)((\.\d+)?)$/, function (s, s1, s2) {
      return s1.replace(re, "$&,") + s2;
    });
    return n1;
  }
}

module.exports = new Utils